﻿libModule.provider("notification", [function () {
    "use strict";
    var _messages = {};
    function handleResponseSucess(data) {        
        toastr.success(_messages.success());
    }

    function handleResponseBrokenRules(data){
        if (data.BrokenRules && data.BrokenRules.length > 0) {
            var brokenRules = "";
            var i;
            for (i = 0; i < data.BrokenRules.length; i++)
                brokenRules += data.BrokenRules[i].PropertyName + " : " + data.BrokenRules[i].Rule + "<br />";
            toastr.warning(brokenRules);
        } 
    }

    function handleErrorResponse(data) {
        if (data.ErrorMessage)
            toastr.error(data.ErrorMessage);
    }

    function handleResponse(data) {
        var i, brokenRules;
        try {
            if (data.ShowNotification && data.ShowNotification === true) {
                if (data.Success)
                    handleResponseSucess(data);
                else {
                    handleErrorResponse(data)
                    handleResponseBrokenRules(data);
                }
            }
        } catch (e) {
            error(e);
        }
    };

    function error(e) {
        console.error(e);
        toastr.error(e.message);        
    };

    function info(message) {
        toastr.info(message);
    }    

    function notifyError(message) {
        toastr.error(message);
    }

    function notify(value) {
        if (value instanceof Error) {
            error(value);
            return;
        }

        if (typeof (value) == "object") {
            handleResponse(value);
            return;
        }

        if (typeof (value) == "string")
            info(value);
    };
   
    return {
        notify: notify,
        notifyError : notifyError,
        $get: function () {            
            return {
                notify: notify,
                notifyError : notifyError,
                setMessages: function (messages) { _messages = messages; }
            }
        }
    }  
}]);